﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OAuth2.Provider.IService;
using OAuth2.Repository;
using OAuth2.Framework.Model;
using OAuth2.Repository.Model;
using OAuth2.Framework;

namespace OAuth2.Provider.Service
{
    public class AuthorizationGrantService:IAuthorizationGrantService
    {
        readonly IClientRepository ClientRepo;
        readonly ITokenRepository TokenRepo;

        public AuthorizationGrantService(ITokenRepository tokenRepo, IClientRepository clientRepo)
        {
            TokenRepo = tokenRepo;
            ClientRepo = clientRepo;
        }

        #region IAuthorizationGrantService 成员

        public AuthorizationGrantModel FindAuthorizationGrant(string authorizationCode)
        {
            return TokenRepo.FindAuthorizationGrant(authorizationCode);
        }

        public AuthorizationGrantModel IssueAuthorizationGrant(AuthorizationEndpoint.IAuthorizationContext context)
        {
            AuthorizationGrantModel grant = new AuthorizationGrantModel();
            Client client = ClientRepo.FindClient(context.Client.ClientID);
            grant.Client = client;
            grant.ResourceOwnerID = context.ResourceOwnerUsername;
            grant.IsApproved = false;
            grant.ExpiresIn = 120;
            grant.Code = Guid.NewGuid().ToString();

            TokenRepo.AddAuthorizationGrant(grant);
            return grant;
        }

        public void ConsumeGrant(AuthorizationGrantModel grant)
        {
            AuthorizationGrantModel gr = (AuthorizationGrantModel)grant;
            gr.IsUsed = true;
            TokenRepo.AddAuthorizationGrant(gr);
        }

        public bool ValidateGrant(ITokenContext context,AuthorizationGrantModel grant)
        {
            return true;
        }

        #endregion
    }
}
